<template>
  <Layout :user="user" :on-logout="handleLogout">
    <div class="todays-records-container">
    <div class="page-header">
      <h1>今日核验记录</h1>
    </div>
    
    <!-- 查询条件区域 -->
    <div class="query-section">
      <el-card>
        <el-form ref="searchFormRef" :model="searchForm" inline label-width="100px">
          <el-form-item label="访客姓名">
            <el-input v-model="searchForm.visitorName" placeholder="请输入访客姓名" style="width: 200px" />
          </el-form-item>
          <el-form-item label="核验结果">
            <el-select v-model="searchForm.verifyResult" placeholder="请选择核验结果" style="width: 150px">
              <el-option label="全部" value="" />
              <el-option label="成功" value="success" />
              <el-option label="拒绝" value="reject" />
              <el-option label="待审核" value="pending" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    
    <!-- 数据统计区域 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon success">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ successCount }}</div>
                <div class="stat-label">成功核验</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon danger">
                <el-icon><CircleClose /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ rejectCount }}</div>
                <div class="stat-label">拒绝核验</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon warning">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ pendingCount }}</div>
                <div class="stat-label">待审核</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon info">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ totalCount }}</div>
                <div class="stat-label">今日总计</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 表格数据区域 -->
    <div class="table-section">
      <el-card>
        <div class="table-header">
          <el-button type="primary" @click="handleExport">导出记录</el-button>
        </div>
        <el-table v-loading="loading" :data="recordsData" border style="width: 100%" class="bg-light-bg-secondary dark:bg-dark-bg-secondary blue:bg-blue-bg-secondary text-light-text-primary dark:text-dark-text-primary blue:text-blue-text-primary">
          <el-table-column prop="id" label="记录ID" width="80" />
          <el-table-column prop="visitorName" label="访客姓名" width="120" />
          <el-table-column prop="visitorPhone" label="联系电话" width="150" />
          <el-table-column prop="visitorType" label="访客类型" width="120">
            <template #default="scope">
              <el-tag :type="getVisitorTypeTag(scope.row.visitorType)">{{ getVisitorTypeText(scope.row.visitorType) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="guardPoint" label="核验点" width="100" />
          <el-table-column prop="verifyResult" label="核验结果" width="100">
            <template #default="scope">
              <el-tag :type="getVerifyResultTag(scope.row.verifyResult)">{{ getVerifyResultText(scope.row.verifyResult) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="verifyTime" label="核验时间" width="180" />
          <el-table-column prop="guardName" label="核验人" width="120" />
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button size="small" type="primary" @click="viewDetail(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页控件 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    
    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="核验记录详情" width="600px">
      <div v-if="currentRecord" class="record-detail">
        <div class="detail-row">
          <span class="detail-label">记录ID：</span>
          <span class="detail-value">{{ currentRecord.id }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">访客姓名：</span>
          <span class="detail-value">{{ currentRecord.visitorName }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">联系电话：</span>
          <span class="detail-value">{{ currentRecord.visitorPhone || '无' }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">访客类型：</span>
          <span class="detail-value">{{ getVisitorTypeText(currentRecord.visitorType) }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">特殊访客：</span>
          <span class="detail-value">{{ currentRecord.specialVisitorFlag ? '是' : '否' }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">核验点：</span>
          <span class="detail-value">{{ currentRecord.guardPoint }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">核验结果：</span>
          <span class="detail-value">{{ getVerifyResultText(currentRecord.verifyResult) }}</span>
        </div>
        <div v-if="currentRecord.rejectionReason" class="detail-row">
          <span class="detail-label">拒绝原因：</span>
          <span class="detail-value">{{ currentRecord.rejectionReason }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">核验时间：</span>
          <span class="detail-value">{{ currentRecord.verifyTime }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">核验人：</span>
          <span class="detail-value">{{ currentRecord.guardName }}</span>
        </div>
      </div>
    </el-dialog>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Check, CircleClose, Clock, Document } from '@element-plus/icons-vue'
import service from '../../utils/request'
import type { VerificationRecord } from '../../types/verification'
import Layout from '../../components/common/Layout.vue'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'

// 使用auth store
const authStore = useAuthStore()
const router = useRouter()

// Layout组件需要的user props
const user = computed(() => ({
  name: authStore.userInfo?.name || '未知用户',
  role: authStore.userInfo?.role || 'guard',
  phone: authStore.userInfo?.phone || undefined,
  district: undefined // 根据实际情况设置
}))

// Layout组件需要的onLogout回调
const handleLogout = () => {
  authStore.logout()
  router.push('/login')
}

// 定义接口类型
interface SearchForm {
  visitorName: string
  verifyResult: string
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

// 路由实例 - 注释掉未使用的变量
// const router = useRouter()

// 响应式数据
const searchForm = reactive<SearchForm>({
  visitorName: '',
  verifyResult: ''
})

// 添加正确的ref引用
const searchFormRef = ref()

const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

const recordsData = ref<VerificationRecord[]>([])
const currentRecord = ref<VerificationRecord | null>(null)
const detailDialogVisible = ref(false)
const loading = ref(false)
// const searchFormRef = ref<FormInstance>()

// 统计数据
const successCount = ref(0)
const rejectCount = ref(0)
const pendingCount = ref(0)
const totalCount = computed(() => successCount.value + rejectCount.value + pendingCount.value)

// 获取今日日期范围
const getTodayDateRange = () => {
  const today = new Date()
  const startOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0).toISOString()
  const endOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59).toISOString()
  return { startOfDay, endOfDay }
}

// 获取访客类型标签样式
const getVisitorTypeTag = (type: string): string => {
  const typeMap: Record<string, string> = {
    'regular': 'info',
    'special': 'primary',
    'temporary': 'warning',
    'vip': 'success'
  }
  return typeMap[type] || 'info'
}

// 获取访客类型文本
const getVisitorTypeText = (type: string): string => {
  const typeMap: Record<string, string> = {
    'regular': '普通访客',
    'special': '特殊访客',
    'temporary': '临时访客',
    'vip': 'VIP访客'
  }
  return typeMap[type] || type
}

// 获取核验结果标签样式
const getVerifyResultTag = (result: string): string => {
  const resultMap: Record<string, string> = {
    'success': 'success',
    'reject': 'danger',
    'pending': 'warning'
  }
  return resultMap[result] || 'info'
}

// 获取核验结果文本
const getVerifyResultText = (result: string): string => {
  const resultMap: Record<string, string> = {
    'success': '成功',
    'reject': '拒绝',
    'pending': '待审核'
  }
  return resultMap[result] || result
}

// 加载今日记录
const loadTodaysRecords = async () => {
  loading.value = true
  try {
    const { startOfDay, endOfDay } = getTodayDateRange()
    
    const params = {
      skip: (pagination.currentPage - 1) * pagination.pageSize,
      limit: pagination.pageSize,
      visitor_name: searchForm.visitorName,
      verify_result: searchForm.verifyResult,
      start_time: startOfDay,
      end_time: endOfDay
    }
    
    const response = await service.get('/api/qrcode/verification-records', { params })
    
    // 正确处理API响应格式
    if (response.data && response.data.records) {
      recordsData.value = response.data.records
      pagination.total = response.data.total
      
      // 计算统计数据
      successCount.value = response.data.records.filter((record: VerificationRecord) => record.verifyResult === 'success').length
      rejectCount.value = response.data.records.filter((record: VerificationRecord) => record.verifyResult === 'reject').length
      pendingCount.value = response.data.records.filter((record: VerificationRecord) => record.verifyResult === 'pending').length
    } else {
      // 如果响应格式不符合预期，设置空数据
      recordsData.value = []
      pagination.total = 0
      successCount.value = 0
      rejectCount.value = 0
      pendingCount.value = 0
    }
  } catch (error) {
    console.error('加载今日记录失败:', error)
    ElMessage.error('加载今日记录失败，请重试')
    // 发生错误时也重置数据
    recordsData.value = []
    pagination.total = 0
    successCount.value = 0
    rejectCount.value = 0
    pendingCount.value = 0
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleSearch = () => {
  pagination.currentPage = 1
  loadTodaysRecords()
}

// 重置搜索条件
const resetSearch = () => {
  searchForm.visitorName = ''
  searchForm.verifyResult = ''
  pagination.currentPage = 1
  loadTodaysRecords()
}

// 分页大小变更
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  loadTodaysRecords()
}

// 当前页码变更
const handleCurrentChange = (current: number) => {
  pagination.currentPage = current
  loadTodaysRecords()
}

// 查看详情
const viewDetail = (record: VerificationRecord) => {
  currentRecord.value = record
  detailDialogVisible.value = true
}

// 导出记录
const handleExport = () => {
  ElMessage.success('正在准备导出数据...')
  // 这里可以实现导出功能，例如调用后端API生成Excel并下载
  // 由于目前未实现完整的导出API，暂时只显示提示信息
}

// 组件挂载时加载数据
onMounted(() => {
  loadTodaysRecords()
})
</script>

<style scoped>
.todays-records-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 20px;
  color: var(--text-primary);
}

.query-section {
  margin-bottom: 20px;
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
}

.stat-icon.success {
  background-color: #f0f9eb;
  color: #67c23a;
}

.stat-icon.danger {
  background-color: #fef0f0;
  color: #f56c6c;
}

.stat-icon.warning {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.stat-icon.info {
  background-color: #edf2fc;
  color: #409eff;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--text-primary);
}

.stat-label {
  font-size: 14px;
  color: var(--text-tertiary);
  margin-top: 4px;
}

.table-section {
  margin-bottom: 20px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-end;
}

.pagination-section {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.record-detail {
  padding: 10px 0;
}

.detail-row {
  display: flex;
  margin-bottom: 12px;
  line-height: 28px;
}

.detail-label {
  width: 100px;
  color: var(--text-tertiary);
  text-align: right;
  padding-right: 16px;
}

.detail-value {
  flex: 1;
  color: var(--text-primary);
}

/* 表格单元格主题样式 */
:deep(.el-table) {
  --el-table-bg-color: transparent;
}

:deep(.el-table__cell) {
  color: var(--text-primary);
}

:deep(.el-table__header-wrapper th.el-table__cell) {
  color: var(--text-primary);
  background-color: var(--bg-secondary);
  border-bottom-color: var(--border);
}

:deep(.el-table__body-wrapper .el-table__row.el-table__row--striped td.el-table__cell) {
  background-color: rgba(0, 0, 0, 0.02);
}

:deep(.el-table__body-wrapper .el-table__row:hover td.el-table__cell) {
  background-color: var(--bg-tertiary);
}

/* 分页控件主题样式 */
:deep(.el-pagination) {
  --el-pagination-item-color: var(--text-primary);
  --el-pagination-item-bg-color: var(--bg-secondary);
  --el-pagination-item-hover-bg-color: var(--bg-tertiary);
  --el-pagination-item-active-bg-color: var(--accent-color);
  --el-pagination-button-disabled-color: var(--text-tertiary);
}

:deep(.el-pagination__total),
:deep(.el-pagination__sizes) {
  color: var(--text-primary);
}
</style>